#include "facedetection.h"
#include <QBuffer>
#include <QJsonObject>
#include <QJsonDocument>
#include <QImage>
#include <QJsonArray>
#include <QDebug>


facedetection::facedetection(QWidget *parent)
{
    this->manager = new QNetworkAccessManager();
    this->accessToken = "24.294c2ad6e4ac3959f6baca5a610a0dcd.2592000.1665020589.282335-26537673";
    //addGroup();
}

facedetection::~facedetection()
{
}

//注册用户组
void facedetection::addGroup(){
    serverApiUrl = QString(server_api).arg("faceset/group/add").arg(accessToken);

    //打包请求参数 ；
    QJsonDocument document;

    QJsonObject para_obj;
    para_obj.insert("group_id", "0624_1835");

    QByteArray post_param = QJsonDocument(para_obj).toJson(QJsonDocument::Compact);

    requestNetwork(serverApiUrl, post_param, 0); //0：创建用户组
}
//人脸注册
void facedetection::addFace(QImage image, QString user_name){
    serverApiUrl = QString(server_api).arg("faceset/user/add").arg(accessToken);
    QByteArray ba;
    QBuffer buffer(&ba);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer, "png"); 
    
    QString imgData = QString(ba.toBase64());//将图片进行BASE64编码
    buffer.close();
    QJsonDocument document;//打包请求参数 ；
    QJsonObject img_obj_1;
    img_obj_1.insert("image", imgData);
    img_obj_1.insert("image_type", "BASE64");
    img_obj_1.insert("quality_control", "LOW");
    img_obj_1.insert("group_id", group_id);
    img_obj_1.insert("user_info", user_name);
    QDateTime time1 = QDateTime::currentDateTime();   //获取当前时间
    QString timeID = QString::number(time1.toTime_t());   //将当前时间转为时间戳

    img_obj_1.insert("user_id", timeID);
    qDebug() << timeID;
    QByteArray post_param = QJsonDocument(img_obj_1).toJson(QJsonDocument::Compact);
    requestNetwork(serverApiUrl, post_param, 1); //1：注册用户
}

//1:N人脸搜索，阈值为80
void facedetection::searchFace(QImage image){
    serverApiUrl = QString(server_api).arg("search").arg(accessToken);
    QByteArray ba;
    QBuffer buffer(&ba);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer, "png"); //记得改正!
    //将图片进行BASE64编码
    QString imgData = QString(ba.toBase64());
    buffer.close();

    //打包请求参数 ；
    QJsonDocument document;

    QJsonObject img_obj_1;
    img_obj_1.insert("image", imgData);
    img_obj_1.insert("image_type", "BASE64");
    img_obj_1.insert("quality_control", "LOW");
    img_obj_1.insert("group_id_list", group_id);

    QByteArray post_param = QJsonDocument(img_obj_1).toJson(QJsonDocument::Compact);
    requestNetwork(serverApiUrl, post_param, 2); //2：人脸搜索
}

void facedetection::getUserList(){
    qDebug() << "进入getUserList";
    serverApiUrl = QString(server_api).arg("faceset/group/getusers").arg(accessToken);
    //打包请求参数 ；
    QJsonDocument document;

    QJsonObject obj;
    obj.insert("group_id", group_id);
    QByteArray post_param = QJsonDocument(obj).toJson(QJsonDocument::Compact);
    requestNetwork(serverApiUrl, post_param, 3); //3: （指定组）用户列表查询
}

void facedetection::getUserInfo(QString user_id){
    curUserId = user_id;
    serverApiUrl = QString(server_api).arg("faceset/user/get").arg(accessToken);
    //打包请求参数 ；
    QJsonDocument document;

    QJsonObject obj;
    obj.insert("user_id", user_id);
    obj.insert("group_id", group_id);
    QByteArray post_param = QJsonDocument(obj).toJson(QJsonDocument::Compact);
    requestNetwork(serverApiUrl, post_param, 4); //4: （指定组）查询单个用户信息
}

void facedetection::delFace(QString user_id){
    qDebug() << "进入";
    serverApiUrl = QString(server_api).arg("faceset/user/delete").arg(accessToken);
    //打包请求参数 ；
    QJsonDocument document;
    QJsonObject obj;
    obj.insert("user_id", user_id);
    obj.insert("group_id", group_id);
    QByteArray post_param = QJsonDocument(obj).toJson(QJsonDocument::Compact);
    requestNetwork(serverApiUrl, post_param, 5); //5: （指定组）删除用户
}

void facedetection::delFaceByName(QString user_name){
    curUserName = user_name;
    serverApiUrl = QString(server_api).arg("faceset/group/getusers").arg(accessToken);
    //打包请求参数 ；
    QJsonDocument document;

    QJsonObject obj;
    obj.insert("group_id", group_id);
    QByteArray post_param = QJsonDocument(obj).toJson(QJsonDocument::Compact);
    requestNetwork(serverApiUrl, post_param, 6); //6: （指定组、用户名）删除用户，首先要用户列表查询
}

/* 请求网络 */
void facedetection::requestNetwork(QString url, QByteArray requestData, int opt)
{
    /* 网络请求 */
    QNetworkRequest networkRequest;

    /* 开发板需要加一些安全配置才能访问https */
    QSslConfiguration config;
    config.setPeerVerifyMode(QSslSocket::VerifyNone);
    config.setProtocol(QSsl::TlsV1SslV3);
    networkRequest.setSslConfiguration(config);

    /* 以json格式返回 */
    networkRequest.setHeader(QNetworkRequest::ContentTypeHeader,
                             "application/json;charset=UTF-8");

    /* 设置访问的地址 */
    networkRequest.setUrl(url);

    /* 网络响应 */
    QNetworkReply *newReply = manager->post(networkRequest, requestData);
    connect(newReply, SIGNAL(finished()), this, SLOT(replyFinished()));
    if(opt == 0){
        connect(newReply, SIGNAL(readyRead()), this, SLOT(readReadAddGroup()));
    }
    else if(opt == 1){
        connect(newReply, SIGNAL(readyRead()), this, SLOT(readReadAddFace()));
    }
    else if(opt == 2){
        connect(newReply, SIGNAL(readyRead()), this, SLOT(readReadSearchFace()));
    }
    else if(opt == 3){
        connect(newReply, SIGNAL(readyRead()), this, SLOT(readReadUserList()));
    }
    else if(opt == 4){
        connect(newReply, SIGNAL(readyRead()), this, SLOT(readReadUserInfo()));
    }
    else if(opt == 5){
        connect(newReply, SIGNAL(readyRead()), this, SLOT(readReadUserDel()));
    }
    else if(opt == 6){
        connect(newReply, SIGNAL(readyRead()), this, SLOT(readReadUserList2()));
    }
}

/* 请求完成处理，释放对象 */
void facedetection::replyFinished()
{
    QNetworkReply *reply = (QNetworkReply *)sender();

    reply->deleteLater();
    reply = nullptr;
}

void facedetection::readReadAddGroup(){
    QNetworkReply *reply = (QNetworkReply *)sender();
    QByteArray replydata = reply->readAll();
    qDebug()<<"创建用户组" << QString(replydata);
}

void facedetection::readReadAddFace(){
    QNetworkReply *reply = (QNetworkReply *)sender();
    QByteArray replydata = reply->readAll();
    qDebug()<<"注册人脸" << QString(replydata);

    QJsonParseError json_error;
    QJsonDocument document = QJsonDocument::fromJson(replydata, &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        QJsonObject obj = document.object();
        int errorCode = obj.take("error_code").toInt();
        QString error_info = obj.take("error_msg").toString();
        emit faceRes(1, errorCode, error_info);
    }
}

void facedetection::readReadSearchFace(){
    QNetworkReply *reply = (QNetworkReply *)sender();
    QByteArray replydata = reply->readAll();
    qDebug()<<"人脸搜索" << QString(replydata);

    QJsonParseError json_error;
    QJsonDocument document = QJsonDocument::fromJson(replydata, &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        QJsonObject obj = document.object();

        int errorCode = obj.take("error_code").toInt();
        if(errorCode == 0){

            QJsonArray user_list = obj.take("result").toObject().take("user_list").toArray();
            qDebug() << user_list;
            QJsonObject obj1 = user_list.at(0).toObject();
            qDebug() << obj1;
            QString user_name = obj1.take("user_info").toString();
            double score = obj1.take("score").toDouble();
            emit faceRes(2, errorCode, user_name + "," + QString::number(score, 'f', 4));
        }
        else {
            QString error_info = obj.take("error_msg").toString();
            emit faceRes(2, errorCode, error_info);
        }

    }
}

void facedetection::readReadUserList(){
    qDebug()<<"readReadUserList";
    QNetworkReply *reply = (QNetworkReply *)sender();
    QByteArray replydata = reply->readAll();
    qDebug()<<"用户列表查询" << QString(replydata);

    QJsonParseError json_error;
    QJsonDocument document = QJsonDocument::fromJson(replydata, &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        QJsonObject obj = document.object();

        int errorCode = obj.take("error_code").toInt();
        if(errorCode == 0){

            QJsonArray user_list = obj.take("result").toObject().take("user_id_list").toArray();
            qDebug() << user_list;
            QString res_str;
            for(auto user : user_list){
                if(res_str == "")
                    res_str = user.toString();
                else
                    res_str = res_str + "," + user.toString();
            }
            qDebug() << res_str;
            emit faceRes(3, errorCode, res_str);
        }
        else {
            QString error_info = obj.take("error_msg").toString();
            emit faceRes(3, errorCode, error_info);
        }
    }
}

void facedetection::readReadUserList2(){
    QNetworkReply *reply = (QNetworkReply *)sender();
    QByteArray replydata = reply->readAll();
    qDebug()<<"用户列表查询" << QString(replydata);

    QJsonParseError json_error;
    QJsonDocument document = QJsonDocument::fromJson(replydata, &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        QJsonObject obj = document.object();

        int errorCode = obj.take("error_code").toInt();
        if(errorCode == 0){

            QJsonArray user_list = obj.take("result").toObject().take("user_id_list").toArray();
            qDebug() << user_list;
            QString res_str;
            for(auto user : user_list){
                if(res_str == "")
                    res_str = user.toString();
                else
                    res_str = res_str + "," + user.toString();
            }
            qDebug() << res_str;
            emit faceRes(6, errorCode, res_str);
        }
        else {
            QString error_info = obj.take("error_msg").toString();
            emit faceRes(6, errorCode, error_info);
        }
    }
}

void facedetection::readReadUserInfo(){
    QNetworkReply *reply = (QNetworkReply *)sender();
    QByteArray replydata = reply->readAll();
    qDebug()<<"用户信息查询" << QString(replydata);

    QJsonParseError json_error;
    QJsonDocument document = QJsonDocument::fromJson(replydata, &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        QJsonObject obj = document.object();

        int errorCode = obj.take("error_code").toInt();
        if(errorCode == 0){

            QJsonArray user_list = obj.take("result").toObject().take("user_list").toArray();
            QJsonObject obj1 = user_list.at(0).toObject();
            QString user_name = obj1.take("user_info").toString();
            qDebug() << user_name;
            emit faceRes(4, errorCode, user_name);
        }
        else {
            QString error_info = obj.take("error_msg").toString();
            emit faceRes(4, errorCode, error_info);
        }
    }
}

void facedetection::readReadUserDel(){
    QNetworkReply *reply = (QNetworkReply *)sender();
    QByteArray replydata = reply->readAll();
    qDebug()<<"删除用户" << QString(replydata);
    QJsonParseError json_error;
    QJsonDocument document = QJsonDocument::fromJson(replydata, &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        QJsonObject obj = document.object();
        int errorCode = obj.take("error_code").toInt();
        QString error_info = obj.take("error_msg").toString();
        emit faceRes(5, errorCode, error_info);
    }
}


